package com.citusdata.elven.feeder;

import com.citusdata.elven.httpRpc.HttpRpcChannelManager;
import com.citusdata.elven.httpRpc.HttpRpcChannel;
import com.citusdata.elven.httpRpc.HttpRpcController;
import com.citusdata.elven.linearRoad.protobuf.LinearRoad.*;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.Message;
import java.util.concurrent.Callable;


// Helper class that makes Rpc over Http calls to a server running LinearRoad.
public class LinearRoadClient implements Callable {
  private static final HttpRpcChannelManager manager = new HttpRpcChannelManager();

  private final String host;
  private final int    port;
  private final Message request;

  public LinearRoadClient(String host, int port, Message request) {
    this.host = host;
    this.port = port;
    this.request = request;
  }

  public static HttpRpcChannelManager manager() {
    return manager;
  }

  public Message call() {
    HttpRpcChannel httpChannel = manager.getChannel(host, port);
    HttpRpcController httpController = new HttpRpcController();

    LinearRoadServiceInterface service = LinearRoadServiceInterface.newStub(httpChannel);
    Callback done = new Callback();
    
    // The only remote interface provided by LinearRoadService is reportPosition.
    if (request instanceof PositionRequest) {
      PositionRequest positionRequest = (PositionRequest) request;
      service.reportPosition(httpController, positionRequest, done); 
    }

    manager.releaseChannel(httpChannel);

    Message response = done.getResponse();
    return response;
  }

  private class Callback implements RpcCallback {
    Message response = null;

    public void run(Object object) {
      response = (Message) object;
    }

    public Message getResponse() {
      return response;
    }
  }
}
